package rmi.server;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import javax.rmi.PortableRemoteObject;
import rmi.OrderItem;
import rmi.Product;
import rmi.WareHouse;
import rmi.server.Order.OrderTuple;

public class WareHouseImpl extends PortableRemoteObject implements WareHouse {

    private List<Product> productList;
    private List<Order> orderList = new ArrayList<Order>();
    private int currentOrderIndex = 1;

    public WareHouseImpl(List<Product> someList) throws RemoteException {
        productList = someList;
    }

    private Order getOrder(int orderNr) {
        System.out.println("Fetching order with orderNr: " + orderNr);
        boolean found = false;
        Order o = null;
        for (int i = 0; i < orderList.size() && !found; i++) {
            if (orderList.get(i).getOrderNr() == orderNr) {
                o = orderList.get(i);
                System.out.println("Found it!");
                found = true;
            }
        }
        return o;
    }

    @Override
    public List<Product> getProductsList() throws RemoteException {
        System.out.println("Fetching product list");
        return productList;
    }

    @Override
    public int addNewOrder(String clientName) throws RemoteException {
        System.out.println("Created new order for: " + clientName + " with nr: " + currentOrderIndex);
        Order o = new Order();
        o.setClientName(clientName);
        o.setOrderNr(currentOrderIndex);
        orderList.add(o);
        return currentOrderIndex++;
    }

    @Override
    public boolean addOrderItem(OrderItem oi) throws RemoteException {
        System.out.println("Created new item for: " + oi.getCustomerName() + " with nr: " + oi.getOrderId());
        Order o = getOrder(oi.getOrderId());
        return o.addTuple(oi.getAmount(), productList.get(oi.getProductId()));
    }

    @Override
    public String getOrderSummary(String clientName, int orderNr) throws RemoteException {
        System.out.println("Fetching order summary for: " + clientName + " with order nr: " + orderNr);
        String summary = null;
        Order o = getOrder(orderNr);
        if (o != null) {
            summary = o.getSummary();
        }
        return summary;
    }

    @Override
    public boolean confirmOrder(String clientName, int orderNr) throws RemoteException {
        System.out.println("Confirming order for: " + clientName + " with order nr: " + orderNr);
        Order o = getOrder(orderNr);
        if (o != null && !o.isConfirmed()) {
            o.setIsConfirmed(true);
            return true;
        }
        return false;
    }
}
